import { HolderOutlined, MenuOutlined, PlusOutlined } from '@ant-design/icons';
import type { DragEndEvent } from '@dnd-kit/core';
import { DndContext } from '@dnd-kit/core';
import { restrictToVerticalAxis } from '@dnd-kit/modifiers';
import {
    arrayMove,
    SortableContext,
    useSortable,
    verticalListSortingStrategy,
} from '@dnd-kit/sortable';
import { CSS } from '@dnd-kit/utilities';
import React, { useEffect, useState } from 'react';
import { Button, Table, message } from 'antd';
import type { ColumnsType } from 'antd/es/table';
import { BetaSchemaForm } from '@ant-design/pro-components';
import { addFormField } from '../service';
import './index.less'

interface RowProps extends React.HTMLAttributes<HTMLTableRowElement> {
    'data-row-key': string;
}

const Row = ({ children, ...props }: RowProps) => {
    const {
        attributes,
        listeners,
        setNodeRef,
        setActivatorNodeRef,
        transform,
        transition,
        isDragging,
    } = useSortable({
        id: props['data-row-key'],
    });

    const style: React.CSSProperties = {
        ...props.style,
        transform: CSS.Transform.toString(transform && { ...transform, scaleY: 1 }),
        transition,
        ...(isDragging ? { position: 'relative', zIndex: 9999 } : {}),
    };

    return (
        <tr {...props} ref={setNodeRef} style={style} {...attributes}>
            {React.Children.map(children, (child) => {
                if ((child as React.ReactElement).key === 'sort') {
                    return React.cloneElement(child as React.ReactElement, {
                        children: (
                            <HolderOutlined
                                ref={setActivatorNodeRef}
                                style={{ touchAction: 'none', cursor: 'move' }}
                                {...listeners}
                            />
                        ),
                    });
                }
                return child;
            })}
        </tr>
    );
};

const App: React.FC<any> = ({
    columns,
    value,
    onChange,
    formType,
    onReload,
    onDragSuccess,
}: any) => {
    const [dataSource, setDataSource] = useState<any[]>([]);
    const [open, setOpen] = useState(false)

    const onDragEnd = ({ active, over }: DragEndEvent) => {
        if (active.id !== over?.id) {
            const activeIndex = dataSource.findIndex((i) => i.key === active.id);
            const overIndex = dataSource.findIndex((i) => i.key === over?.id);
            let newDataSource = arrayMove(dataSource, activeIndex, overIndex);
            newDataSource = newDataSource?.map((item, index) => ({
                ...item,
                sort: index + 1
            }))
            setDataSource(newDataSource);
            onDragSuccess?.(newDataSource)
        }
    };

    useEffect(() => {
        setDataSource(value)
    }, [value])

    return (
        <div className='drag_edit_table' style={open ? { position: 'relative', zIndex: 999 } : undefined}>
            <DndContext modifiers={[restrictToVerticalAxis]} onDragEnd={onDragEnd}>
                <SortableContext
                    // rowKey array
                    items={dataSource.map((i) => i.key)}
                    strategy={verticalListSortingStrategy}
                >
                    <BetaSchemaForm<any>
                        key="primary"
                        onOpenChange={val => {
                            setOpen(val)
                        }}
                        layoutType={'ModalForm'}
                        onFinish={async (values) => {
                            // console.log(values);
                            const hide = message.loading('正在保存');
                            try {
                                const res = await addFormField({
                                    formType: formType,
                                    ...values,
                                    options: values?.options?.join(',')
                                })
                                // console.log('res', res);
                                if (res?.code == 0) {
                                    hide();
                                    message.success('保存成功');
                                    onReload?.()
                                }
                                return true
                            } catch (e) {
                                hide();
                                message.error('保存失败请重试！');
                                return false
                            }
                        }}
                        modalProps={{
                            destroyOnClose: true,
                            title: "新增列",
                            width: "500px",
                        }}
                        trigger={<Button style={{ marginBottom: 20 }}  onClick={() => {

                        }}><PlusOutlined />新增</Button>}
                        columns={columns}
                    />
                    <Table
                        onChange={onChange}
                        components={{
                            body: {
                                row: Row,
                            },
                        }}
                        rowKey="key"
                        columns={columns}
                        dataSource={dataSource}
                        pagination={false}
                    />
                </SortableContext>
            </DndContext>
        </div>
    );
};

export default App;